package per.ethan.springboot.example.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Ethan
 * @date 2020/06/17 11:37
 */
@RestController
@RequestMapping("/user")
public class UserController {

    // 有权限
    @GetMapping("/{id}")
    @RequiresPermissions(value = {"user:id"})
    public String getById(@PathVariable Long id) {
        return "user: " + id;
    }

    // 未授权
    @GetMapping("/test")
    @RequiresPermissions(value = {"user:id2"})
    public String getById() {
        return "user:id2";
    }

    @GetMapping("/login")
    public String login(String username, String password) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        try {
            subject.login(usernamePasswordToken);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return "用户名或密码错误";
        }
        return "login success";
    }

}
